package cn.com.wangluotongxin.merchants.service.impl;

import cn.com.wangluotongxin.common.exceptions.BadResponseException;
import cn.com.wangluotongxin.common.pojo.TenantUser;
import cn.com.wangluotongxin.merchants.dto.GoodsUnitDto;
import cn.com.wangluotongxin.merchants.form.GoodsUnitForm;
import cn.com.wangluotongxin.merchants.model.MerchantsGoodsUnit;
import cn.com.wangluotongxin.merchants.mapper.MerchantsGoodsUnitMapper;
import cn.com.wangluotongxin.merchants.service.IMerchantsGoodsUnitService;
import cn.com.wangluotongxin.merchants.vo.GoodsUnitVo;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 商户管理-商品管理-单位 服务实现类
 * </p>
 *
 * @author AutoGenerator
 * @since 2024-06-26
 */
@Service
public class MerchantsGoodsUnitServiceImpl extends ServiceImpl<MerchantsGoodsUnitMapper, MerchantsGoodsUnit> implements IMerchantsGoodsUnitService {

    @Override
    public IPage<GoodsUnitVo> getPage(GoodsUnitDto dto) {
        Page page = Page.of(dto.getPageNumber(), dto.getPageSize());
        return baseMapper.getPage(page, dto);
    }

    @Override
    public List<GoodsUnitVo> getList() {
        return baseMapper.getList();
    }

    @Override
    public void add(GoodsUnitForm form, TenantUser tenantUser) {
        if(this.count(new LambdaQueryWrapper<MerchantsGoodsUnit>()
                .eq(MerchantsGoodsUnit::getUnitName, form.getUnitName())) > 0) {
            throw new BadResponseException("单位【" + form.getUnitName() + "】已存在");
        }
        MerchantsGoodsUnit goodsUnit = new MerchantsGoodsUnit();
        BeanUtils.copyProperties(form, goodsUnit);
        goodsUnit.setCreateUser(tenantUser.getId());
        goodsUnit.setCreateName(tenantUser.getUsername());
        goodsUnit.setCreateTime(DateUtil.date());
        this.save(goodsUnit);
    }

    @Override
    public void enabled(Integer id, Integer isEnabled) {
        this.update(new LambdaUpdateWrapper<MerchantsGoodsUnit>()
                .set(MerchantsGoodsUnit::getIsEnabled, isEnabled)
                .eq(MerchantsGoodsUnit::getId, id));
    }
}
